package com.jason.kotlin.activityresult

import android.app.Activity
import android.net.Uri
import android.os.Environment
import android.util.Log
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.jason.kotlin.model.ActivityResultEntity
import com.jason.kotlin.utils.showToast
import java.io.File


/**
 * Description:MyLifecycleObserver
 *
 * @author chenbaoyang
 * @create 2021/1/14 17:45
 */
class MyLifecycleObserver(
    private val registry: ActivityResultRegistry,
    private val listener: ActivityResultListener
) : DefaultLifecycleObserver {


    /**
     * ActivityResultContracts提供的以下几种常用的封装方法
     *
     * RequestMultiplePermissions : 多个权限请求
     * RequestPermission : 单个权限请求
     * TakePicturePreview : 拍照预览
     * TakePicture : 拍照
     * TakeVideo : 摄像
     * PickContact : 选择联系人
     * GetContent : 获取各种文件的Uri
     * GetMultipleContents : 获取多个各种文件的Uri
     * OpenDocument : 打开文件
     * OpenMultipleDocuments : 打开多个文件
     * OpenDocumentTree : 打开文件夹
     * CreateDocument : 创建文件
     */

    companion object {
        /**
         * 日志的标识
         */
        const val TAG = "MyLifecycleObserver"

        /**
         * Activity Result 中 getContent()的对应回调key
         */
        const val KEY_GET_CONTENT = "getContent"

        /**
         * Activity Result 中 OpenDocument()的对应回调key
         */
        const val KEY_OPEN_DOCUMENT = "OpenDocument"

        /**
         * Activity Result 中 RequestPermission()的对应回调key
         */
        const val KEY_REQUEST_PERMISSION = "requestPermission"

        /**
         * Activity Result 中 RequestMultiplePermissions()的对应回调key
         */
        const val KEY_REQUEST_MULTI_PERMISSION = "requestMultiPermission"

        /**
         * Activity Result 中 TakePicturePreview()的对应回调key
         */
        const val KEY_TAKE_PICTURE_PREVIEW = "takePicturePreview"

        /**
         * Activity Result 中 TakePicture()的对应回调key
         */
        const val KEY_TAKE_PICTURE = "takePicture"

        /**
         * Activity Result 中 TakeVideo()的对应回调key
         */
        const val KEY_TAKE_VIDEO = "takeVideo"

        /**
         * Activity Result 中 PickContact()的对应回调key
         */
        const val KEY_PICK_CONTACT = "pickContact"
    }

    lateinit var getContent: ActivityResultLauncher<String>

    lateinit var openDocument: ActivityResultLauncher<Array<String>>

    lateinit var requestPermission: ActivityResultLauncher<String>

    lateinit var requestMultiPermission: ActivityResultLauncher<Array<String>>

    lateinit var takePicturePreview: ActivityResultLauncher<Void>

    lateinit var takePicture: ActivityResultLauncher<Uri>

    lateinit var takeVideo: ActivityResultLauncher<Uri>

    lateinit var pickContact: ActivityResultLauncher<Void>

    override fun onCreate(owner: LifecycleOwner) {
        getContent = registry.register(
            KEY_GET_CONTENT,
            owner,
            ActivityResultContracts.GetContent(),
            ActivityResultCallback<Uri> {
                if (it != null) {
                    Log.i(TAG, it.toString())

                    callBack(ActivityResultEntity(KEY_GET_CONTENT, it))
                }

            })

        openDocument = registry.register(
            KEY_OPEN_DOCUMENT,
            owner,
            ActivityResultContracts.OpenDocument(),
            ActivityResultCallback<Uri> {
                if (it != null) {
                    Log.i(TAG, it.toString())
                    callBack(ActivityResultEntity(KEY_OPEN_DOCUMENT, it))
                }
            })

        requestPermission = registry.register(
            KEY_REQUEST_PERMISSION,
            owner,
            ActivityResultContracts.RequestPermission(),
            ActivityResultCallback {
                callBack(ActivityResultEntity(KEY_REQUEST_PERMISSION, it))
            })

        requestMultiPermission = registry.register(
            KEY_REQUEST_MULTI_PERMISSION,
            owner,
            ActivityResultContracts.RequestMultiplePermissions(),
            ActivityResultCallback {
                callBack(ActivityResultEntity(KEY_REQUEST_MULTI_PERMISSION, it))
            })

        takePicturePreview = registry.register(
            KEY_TAKE_PICTURE_PREVIEW,
            owner,
            ActivityResultContracts.TakePicturePreview(),
            ActivityResultCallback {
                it?.let { callBack(ActivityResultEntity(KEY_TAKE_PICTURE_PREVIEW, it)) }

            })

        takePicture = registry.register(
            KEY_TAKE_PICTURE,
            owner,
            ActivityResultContracts.TakePicture(),
            ActivityResultCallback {
                callBack(ActivityResultEntity(KEY_TAKE_PICTURE, it))
            })

        takeVideo = registry.register(
            KEY_TAKE_VIDEO,
            owner,
            ActivityResultContracts.TakeVideo(),
            ActivityResultCallback {
                it?.let {
                    callBack(ActivityResultEntity(KEY_TAKE_VIDEO, it))
                }

            })

        pickContact = registry.register(
            KEY_PICK_CONTACT,
            owner,
            ActivityResultContracts.PickContact(),
            ActivityResultCallback {
                if (it != null) {
                    callBack(ActivityResultEntity(KEY_PICK_CONTACT, it))
                }
            })

    }

    /**
     * 回调
     *
     * @param resultEntity 统一数据基类型
     */
    private fun callBack(resultEntity: ActivityResultEntity) {
        listener.callBack(resultEntity)
    }


    /**
     * 拍照预览
     */
    fun takePicturePreview() {
        takePicturePreview.launch(null)
    }

    /**
     * 拍照
     */
    fun takePicture(activity: Activity) {

        val dirFile = File(Environment.getExternalStorageDirectory().absolutePath + "/KotlinStudio")
        if(!dirFile.exists()) {
            val result = dirFile.mkdir()
            if(result) {
                activity.showToast("创建目录成功")
            }else{
                activity.showToast("创建目录失败")
            }
        }
        val fileName = "${System.currentTimeMillis()}.jpg"
        val file = File(dirFile.path, fileName)
        val uri = FileProvider.getUriForFile(
            activity,
            activity.getApplicationContext().getPackageName().toString() + ".fileProvider",
            file
        )

        takePicture.launch(uri)
    }

    /**
     * 摄像
     */
    fun takeVideo(activity: Activity) {
        val dirFile = File(Environment.getExternalStorageDirectory().absolutePath + "/KotlinStudio")
        if(!dirFile.exists()) {
            val result = dirFile.mkdir()
            if(result) {
                activity.showToast("创建目录成功")
            }else{
                activity.showToast("创建目录失败")
            }
        }
        val path =
            Environment.getExternalStorageDirectory().absolutePath + "/KotlinStudio/" + System.currentTimeMillis() + ".mp4"
        val file = File(path)
        val uri = FileProvider.getUriForFile(
            activity,
            activity.getApplicationContext().getPackageName().toString() + ".fileProvider",
            file
        )

        takeVideo.launch(uri)
    }

    /**
     * 选择联系人
     */
    fun pickContact() {
        pickContact.launch(null)
    }

    /**
     * 获取各种文件的Uri
     */
    fun selectImage() {
        getContent.launch("image/*")
    }

    /**
     * 打开文件
     */
    fun selectFile() {
        openDocument.launch(arrayOf("image/*", "text/plain"))
    }


    /**
     * 申请单个权限
     *
     * @param permission 要申请的权限
     */
    fun requestPermission(permission: String) {
        requestPermission.launch(permission)
    }

    /**
     * 申请多个权限
     *
     * @param permissions 要申请的权限
     */
    fun requestMultiPermission(permissions: Array<String>) {
        requestMultiPermission.launch(permissions)
    }
}